package com.itheima.aspact;

import com.itheima.mapper.LogMapper;
import com.itheima.pojo.EmpLoginLog;
import com.itheima.pojo.Empoto;
import com.itheima.pojo.LoginInfo;
import com.itheima.utils.TliasException;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import com.itheima.pojo.Result;
import java.time.LocalDateTime;

@Aspect
@Component
@Slf4j
public class RecordEmpLoginAdvice {
    @Autowired
    public LogMapper logMapper;

    @Around("execution(* com.itheima.service.impl.EmpServiceImpl.login(..))")
    public Object loginAdvice(ProceedingJoinPoint pjp) throws Throwable {
        Object[] args = pjp.getArgs();
        Empoto empDto = (Empoto) args[0];
        EmpLoginLog empLoginLog = new EmpLoginLog();
        empLoginLog.setUsername(empDto.getUsername());
        empLoginLog.setPassword(empDto.getPassword());
        empLoginLog.setLoginTime(LocalDateTime.now());
        long begin = System.currentTimeMillis();
        long end = 0;
        Object result = null;
        try {
            result = pjp.proceed();
            end = System.currentTimeMillis();
            empLoginLog.setIsSuccess((short) 1);
            LoginInfo loginInfo = (LoginInfo) result;
            empLoginLog.setJwt(loginInfo.getToken());
            empLoginLog.setCostTime(end - begin);
            logMapper.save(empLoginLog);
            return result;
        } catch (Throwable e){
            end = System.currentTimeMillis();
            empLoginLog.setIsSuccess((short) 0);
            empLoginLog.setJwt(null);
            empLoginLog.setCostTime(end - begin);
            logMapper.save(empLoginLog);
            throw new TliasException("用户名或密码错误");
        }
    }
}